

import UIKit
import AFNetworking

/// 网络请求枚举类型，Swift中的枚举可以指定不同的数据类型
enum CZRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
    
    
    let app_key = "1193457754"
    let appSecret = "28d790af136d192ec37980ac2dfa5a10"
    let redirect_uri = "http://www.baidu.com"
    
   /// 单例
    static let sharedTools: NetworkTools = {
        let tools = NetworkTools(baseURL: nil)
        
        //设置AFN的网络请求时长
        tools.requestSerializer.timeoutInterval = 15
        
        // 设置反序列化支持数据格式
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        //将json中null之过滤，有些第三方框架在做字典转模型是，遇到null会奔溃
        (tools.responseSerializer as! AFJSONResponseSerializer).removesKeysWithNullValues = true
        
//        //设置连接状态变化回调
//        tools.reachabilityManager.setReachabilityStatusChangeBlock({ (status) -> Void in
//            
//        })
        
        //启动连接转态监听 - 通过通知中心发布的
        tools.reachabilityManager.startMonitoring()
        
        return tools
    }()
    
    var reachable: Bool{
        
        return reachabilityManager.reachable
    }
    
    deinit{
        //停止连接状态监听
        reachabilityManager.stopMonitoring()
    }
    
    /// 封装 AFN 方法发起网络请求
    ///
    /// - parameter method:     GET / POST
    /// - parameter URLString:  URLString
    /// - parameter parameters: 参数字典
    /// - parameter finished:   完成回调(json字典)
    func request(method: CZRequestMethod, URLString: String, parameters: [String: AnyObject]?, finished: (result: [String: AnyObject]?)->()) {
        
        // 回调方法的参数，可以从 AFN 的方法直接粘贴
        // 成功回调
        let success = { (task: NSURLSessionDataTask, responseObject: AnyObject?) -> Void in
            
            if let result = responseObject as? [String: AnyObject] {
                finished(result: result)
            } else {
                
                print("数据格式错误")
                finished(result: nil)
            }
        }
        // 失败回调
        let failure = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            print("网络请求错误 \(error)")
            finished(result: nil)
        }
        
        if method == .GET {
            // GET 请求
            GET(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else {
            // POST 请求
            POST(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
    }
    
  /// 上传文件
    func upload(URLString: String, parameters: [String: AnyObject]?,data: NSData, name: String,finished: (result: [String: AnyObject]?)->()){
        
    
      
        
        POST(URLString, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
            //data 要上传的二进制数据  name 服务器制定上传的字段名 fileName 文件名谁编写 mimeType
            formData.appendPartWithFileData(data, name: name, fileName: "hell", mimeType: "application/octet-stream")
            
            
            }, progress: nil, success: { (_, responseObject) -> Void in
                
                if let result = responseObject as? [String: AnyObject] {
                    finished(result: result)
                } else {
                    
                    print("数据格式错误")
                    finished(result: nil)
                }
                
            }) { (_, error) -> Void in
               
                print("网络请求错误 \(error)")
                finished(result: nil)
        }
        
        
        
        
    }
}

